<template>
  <div class="homePage">
    <gis-map ref="gisMap" :airport-list="airportsInfo" :param="data.routeParam" @coords="getCoords" @polygon="getPolygon" />
    <div class="recentTaskListWrap">
      <recent-task-list
        ref="RtlRef"
        :airport-list="airportsInfo"
        :gis-map="gisMap"
        :inspection-list="inspectionList"
        class="recentTaskList"
        :class="!openActive ? 'openActive' : ''"
        :create="createType"
        @set-region="handleRegion"
        @open-modal="openModal"
        @new-line="sumbitNewLine"
        @open-live="openLive"
        @open-return="openReturn"
        @change-route-params="handleChangeRouteParams"
        @clear-draw="clearDraw"
      />
      <div class="openActionWrap" :class="!openActive ? 'openActiveBtn' : ''" @click="changeActive">
        <DoubleLeftOutlined v-show="!openActive" />
        <DoubleRightOutlined v-show="openActive" />
      </div>
    </div>
    <new-modal v-if="showModal" :title="'立即执行确认'" @close-modal="close">
      <template #content>
        <div class="contentWrap">
          该任务还未达到时间，确认立即执行么？
        </div>
      </template>
      <template #operator>
        <div class="buttonWrap">
          <div class="button cancel" @click="close">取消</div>
          <div class="button confirm" @click="execute()">确认</div>
        </div>
      </template>
    </new-modal>
    <n-drawer
      v-model:show="showOuter"
      :width="'100%'"
      :on-after-leave="closeDrawer"
    >
      <n-drawer-content :title="selectedInfo.type==='live'?'现场直播':'回放'" closable>
        <draw-content :selected-info="selectedInfo" :airport-list="airportsInfo" :play-video-url-obj="playVideoUrlObj" :video-url="videoUrl" :airport-info="airportInfo" :airportem="airportem" />
      </n-drawer-content>
    </n-drawer>
    <!-- <scroll-info /> -->
    <!-- <gis-map /> -->
  </div>
</template>

<script setup>
import RecentTaskList from '@/views/homePage/components/recentTaskList.vue'
// eslint-disable-next-line no-unused-vars
import GisMap from '@/views/gisMap/index.vue'
// import OlMap from '@/components/OlMap/OlContainer2.vue'
import ScrollInfo from '../../views/homePage/components/scrollInfo.vue'
import { DoubleLeftOutlined, DoubleRightOutlined } from '@vicons/antd'
import { onBeforeMount, onUnmounted, ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { executeTask, getInspectionListHome } from '@/api/home-page'
import { getAirportDetail, getAirportMsg, getTypeVideoType } from '@/api/air-data'
import NewModal from '@/components/newModal/index.vue'
import DrawContent from '@/views/homePage/components/drawContent.vue'
import { addAirportLine } from '@/api/task/index.js'
import { useRoute, useRouter } from 'vue-router'
import { getAirList, getTaskByID, getTaskVideo } from '@/api/task/index.js'

const route = useRoute()
const router = useRouter()
const createType = ref(false)
onMounted(() => {
  if (route.query?.type === 'create' || route.query?.type === 'edit') {
    createType.value = true
  }
})
const closeDrawer = () => {
  getInspectionList()
  timer.value = setInterval(() => {
    getInspectionList()
  }, 3000)
  clearInterval(timer1.value)
  clearInterval(timer2.value)
  clearInterval(timer3.value)
  router.push({
    path: '/home'
  })
}
// 打开关闭抽屉
const openActive = ref(true)
const changeActive = () => {
  openActive.value = !openActive.value
}
const inspectionList = ref([])
const getInspectionList = async() => {
  const data = await getInspectionListHome()
  inspectionList.value = data.data
}
const timer = ref(null)
onBeforeMount(() => {
  getInspectionList()
  timer.value = setInterval(() => {
    getInspectionList()
  }, 3000)
  getAirportList()
  clearInterval(timer1.value)
})
const clearInter = () => {
  if (timer.value === null) return
  clearInterval(timer.value)
  timer.value = null
}

const airportsInfo = reactive([])
function getAirportList() {
  getAirList().then(res => {
    if (res.code === 0) {
      res.data.records
      res.data.records.forEach((e, index) => {
        airportsInfo.push(e)
      })
    }
  })
}
onBeforeUnmount(() => {
  clearInterval(timer1.value)
  clearInterval(timer2.value)
  clearInterval(timer3.value)
})
onUnmounted(() => {
  clearInter()
})
// 任务id
// const taskId = ref(null)
const exexuteInfoData = ref({})
// 立即执行确认弹窗
const showModal = ref(false)
const openModal = (obj) => {
  exexuteInfoData.value = obj
  showModal.value = true
}
// 立即执行弹窗关闭
const close = () => {
  showModal.value = false
}
// 立即执行
const execute = () => {
  executeTask(exexuteInfoData.value.id).then(res => {
    if (res.code === 0) {
      showModal.value = false
      getInspectionList()
      openLive(exexuteInfoData.value)
    } else {
      showModal.value = false
    }
  })
}
const showOuter = ref(false)
// const currentTask = ref()
// const currentAirport = ref()
const selectedInfo = ref()
const openLive = (val) => {
  // console.log('直播', val)
  showOuter.value = true
  const currentTask = val?.id
  const droneId = val?.droneId
  const inspectionType = val?.inspectionType
  const status = val?.status
  const currentAirport = airportsInfo.filter(e => e.id === val?.airportId)
  const startNEnd = [val.startLongitude, val.startLatitude, val.endLongitude, val.endLatitude]
  const inspectionLine = val?.inspectionLine
  selectedInfo.value = {
    currentTask,
    droneId,
    currentAirport,
    inspectionType,
    status,
    startNEnd,
    inspectionLine,
    type: 'live'
  }
  if (val?.airportId && val?.inspectionType !== 3) {
    getAirportTem(val?.airportId)
    scrollStatus(val?.id)
    if (val?.status === 10) {
      scrollGetAirportMsg(val.id)
    }
  }
  if (val?.droneId && val?.inspectionType !== 3) {
    getVideoById(val?.id, val?.droneId)
  } else {
    getVideoUrl(val.id, 'live')
  }
  clearInter()
}
const openReturn = (val) => {
  console.log(val,'val=====')
  const currentTask = val?.id
  const inspectionLine = val?.inspectionLine
  const currentAirport = airportsInfo.filter(e => e.id === val?.airportId)
  const startNEnd = [val.startLongitude, val.startLatitude, val.endLongitude, val.endLatitude]
  selectedInfo.value = {
    currentTask,
    inspectionLine,
    currentAirport,
    type: 'return',
    inspectionType: val.inspectionType,
    startNEnd
  }
  getTaskVideo(currentTask).then(res => {
    if (res.code === 0) {
      videoUrl.value = res.data?.videoUrl
    }
    showOuter.value = true
    console.log(selectedInfo.value,'selectinfo==')
    clearInter()
  })
}
// 根据机场id获取机场信息天气温湿度及挂载状态
const airportem = ref({})
const timer1 = ref(null)
function getAirportTem(id) {
  getAirportDetail(id).then(res => {
    if (res.code === 0) {
      airportem.value = res.data || {}
    }
  })
  timer1.value = setInterval(() => {
    getAirportDetail(id).then(res => {
      if (res.code === 0) {
        airportem.value = res.data || {}
      }
    })
  }, 30000)
}
// 根据任务id获取无人机信息(实时数据)
const airportInfo = ref({})
function getAirportMsgById(id) {
  getAirportMsg(id).then(res => {
    if (res.code === 0) {
      airportInfo.value = res.data || {}
    }
  })
}
const timer2 = ref(null)
function scrollGetAirportMsg(id) {
  timer2.value = setInterval(() => {
    getAirportMsgById(id)
  }, 2000)
}
const timer3 = ref(null)
function scrollStatus(id) {
  getTaskByID(id).then(res => {
    if (res.code === 0) {
      if (res.data.status === 10) {
        getAirportMsgById(id)
      } else {
        clearInterval(timer2.value)
      }
    }
  })
  timer3.value = setInterval(() => {
    getTaskByID(id).then(res => {
      if (res.code === 0) {
        if (res.data.status === 10) {
          getAirportMsgById(id)
        } else {
          clearInterval(timer2.value)
        }
      }
    })
  }, 2000)
}
const gisMap = ref()
const RtlRef = ref()
const data = reactive({
  timer: null,
  timer1: null,
  times: 0,
  // airportSocket: SocketService.Instance,
  quesList: [],
  airport: null,
  airportInfo: {},
  droneMsg: {},
  airportMsg: {},
  airportUrl: null,
  bufferAirportId: null,
  routeParam: null,
  routeCoords: [],
  polygonCoords: [],
  regionList: [], // 区域经纬度列表
  airportLngLat: [],
  airportRouteList: [],
  accidentLayer: null,
  // 飞行轨迹相关
  trackInfo: null,
  accidentVideo: null,
  counter: 0
})

const getCoords = (lngLats) => {
  data.routeCoords = lngLats
}

const getPolygon = (lngLats) => {
  data.polygonCoords = lngLats
}

function handleChangeRouteParams(params) {
  gisMap.value.clearRoute()
  data.routeParam = params
}

const sumbitNewLine = (info) => {
  if (data.routeCoords?.length) {
    const params = {
      airportLineName: info.name,
      airportId: info.airportId,
      airportRouteDtoList: [],
      inspectionRegionDtoList: []
    }
    // data.routeParam = {
    //   angle: info.angle,
    //   intelval: info.intelvalw
    // }
    data.polygonCoords.forEach(e => {
      const item = {
        lng: e[0],
        lat: e[1]
      }
      params.inspectionRegionDtoList.push(item)
    })
    data.routeCoords.forEach(e => {
      const item = {
        altitude: info.altitude,
        lng: e[0],
        lat: e[1]
      }
      params.airportRouteDtoList.push(item)
    })
    addAirportLine(params).then(res => {
      if (res.code === 0 || res.code === -1) {
        clearDraw()
        RtlRef.value.newLineSuccess(res.data)
        RtlRef.value.getAirportLine()
      }
    })
  } else {
    $message.error('请先绘制!')
  }
}

const clearDraw = () => {
  // 清除新建事故中的机场缓冲区和绘制区域
  gisMap.value.clearAirportBuffer()
  gisMap.value.clearRoute()
  gisMap.value.clearDrawGeometry()
  data.bufferAirportId = null
  data.airportLngLat = []
  data.airportRouteList = []
}

function handleRegion(info) {
  if (data.routeCoords?.length || data.routeCoords?.length) {
    data.routeCoords = []
    data.polygonCoords = []
    clearDraw()
    handleRegion(info)
  }
  if (Object.keys(info).length) {
    // 绘制机场覆盖范围缓冲区
    if (info?.airportId) {
      if (info?.airportId !== data.bufferAirportId) {
        data.bufferAirportId = info?.airportId
        data.airportLngLat = [parseFloat(info?.longitude), parseFloat(info?.latitude)]
        gisMap.value.drawAirportBuffer(data.airportLngLat, 2)
        // if (info?.operate !== 'save' & info?.lineType !== null) {
        //   gisMap.value.drawGeometry(info?.lineType)
        // }
      }
    }
    gisMap.value.drawGeometry('Polygon')
  }
}

const videoUrl = ref(null)
function getVideoUrl(taskId, type) {
  getTaskVideo(taskId).then(res => {
    if (res.code === 0) {
      videoUrl.value = type === 'live' ? res.data?.playUrl : res.data?.videoUrl
      // videoUrl.value = type === 'live' ? 'http://192.168.10.101:18000/hls/stream_11/playlist.m3u8' : res.data?.videoUrl
      // const url = type.value === 'live' ? res.aipullUrl : res.aiVideoUrl || getAssetsFile('video/video.mp4')
      // return url
    }
  })
}
// 根据任务id和无人机id获取机场内外视频和直播视频
const playVideoUrlObj = ref({})
function getVideoById(id, droneId) {
  getTypeVideoType(id, droneId).then(res => {
    if (res.code === 0) {
      playVideoUrlObj.value = res.data || {}
    }
  })
}

</script>

<style scoped lang="scss">
  .homePage {
    width: 100%;
    height: 100%;
    .contentWrap{
      color: #fff;
      font-size: 16px;
      padding: 20px 60px;
    }
    .buttonWrap{
      display: flex;
      justify-content: right;
      position: absolute;
      bottom: 40px;
      right: 40px;
      cursor: pointer;
      .button{
        font-size: 14px;
        color: #fff;
        padding: 4px 40px;
        border-radius: 4px;
      }
      .cancel{
        background: #394C73;
        margin-right: 10px;
      }
      .confirm{
        background: #009CFF;
      }
    }
    .recentTaskListWrap {
      .recentTaskList {
        transition: 1s all;
        height: calc(100% - 0px);
        padding: 0 20px 10px 20px;
        background-color: rgba(11,22,34,.9);
        color: #fff;
        position: absolute;
        right: 0;
        top: 0;
        box-shadow: -2px 0px 0px 0px #3B6BEC;;
      }

      .openActionWrap {
        transition: 1s all;
        color: #fff;
        position: absolute;
        height: 80px;
        top: 45%;
        right: 420px;
        width: 30px;
        background: #010512a6;
        line-height: 100px;
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
        box-shadow: -2px 0px 0px 0px #3B6BEC;;
        cursor: pointer;

        svg {
          font-size: 24px;
        }
      }

      .openActive {
        transition: 1s all;
        right: -420px;
      }

      .openActiveBtn {
        transition: 1s all;
        right: 0px;
      }
    }
  }
  .n-drawer {
    background-color: red !important;
  }
</style>
